package com.example.xiaoxueqixiangmu.jiemian;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.HandlerThread;
import android.os.Trace;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.xiaoxueqixiangmu.R;
import com.example.xiaoxueqixiangmu.bean.Order;
import com.example.xiaoxueqixiangmu.bean.Passengers;
import com.example.xiaoxueqixiangmu.bean.Train;
import com.example.xiaoxueqixiangmu.utils.Constant;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class chepiaoyuding3Activity extends AppCompatActivity {
    private TextView add, fromStationName , toStationName , startTime , arriveTime , dur , trainNo , seatName , seatPrice ,allPrice ,up;
    private List<Train> listTrain;
    private List<Passengers> listPassenger;
    private MyAdapter3 smyAdapter3;
    private ArrayList<HashMap<String,String>> sdataArray;
    private ListView lv;
    private String price;
    private String ids = "";
    private String idType = "";
    private ArrayList<String> paArray = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chepiaoyuding3);

        // Layout中的组件的初始化
        fromStationName = findViewById(R.id.fromStationName);
        toStationName = findViewById(R.id.toStationName);
        startTime = findViewById(R.id.startTime);
        arriveTime = findViewById(R.id.arriveTime);
        dur = findViewById(R.id.dur);
        trainNo = findViewById(R.id.tN);
        seatName = findViewById(R.id.seatName);
        seatPrice = findViewById(R.id.seatPrice);
        allPrice = findViewById(R.id.allPrice);
        add = findViewById(R.id.add);
        lv = findViewById(R.id.lv);
        up = findViewById(R.id.up);

        // 从上一个页面中 获取到 出发车次，到达车次，出发时间（年月日），购买的火车型号，购买的座位号，座位数量
        // 座位类型 ， 出发到到达的时间 数据 。
        Intent intent = getIntent();
        String fsn = intent.getStringExtra("fromStationName");
        String tsn = intent.getStringExtra("toStationName");
        final String startTrainDate = intent.getStringExtra("startTrainDate");
        String myear = intent.getStringExtra("myear");
        String mmonth = intent.getStringExtra("mmonth");
        String mday = intent.getStringExtra("mday");
        String snum = intent.getStringExtra("seatNum");
        final String sname = intent.getStringExtra("seatName");
        String stt = intent.getStringExtra("stt");
        String at = intent.getStringExtra("at");
        String dur = intent.getStringExtra("dur");
        final String tn = intent.getStringExtra("tn");
        price = intent.getStringExtra("seatPrice");
        listTrain = (List<Train>) intent.getSerializableExtra("listTrain");

        // 将数据传入数据源，初始化适配器，让数据加载到子项上
        sdataArray = new ArrayList<>();
        smyAdapter3 = new MyAdapter3(this,sdataArray);
        lv.setAdapter(smyAdapter3);

        fromStationName.setText(fsn);
        toStationName.setText(tsn);
        this.dur.setText(dur);
        startTime.setText(stt);
        arriveTime.setText(at);
        trainNo.setText(tn);
        seatName.setText(sname+snum);
        seatPrice.setText(price);

        // 添加乘车人的监听事件，点击添加乘车人，就从服务器获取账号下人员数据，用户可以点击人员进行添加乘车人
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                queryFromServer();
            }
        });

        // 提交按钮的监听事件，向服务器下订单，点击提交将添加的乘车人数据上传到服务器购买车票。
        up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        OkHttpClient okHttpClient = new OkHttpClient();
                        SharedPreferences sharedPreferences = getSharedPreferences("userinfo",MODE_PRIVATE);
                        String JSESSIONID = sharedPreferences.getString("cookie", "");
                        FormBody formBody = new FormBody.Builder()
                                .add("trainNo",tn)
                                .add("startTrainDate",startTrainDate)
                                .add("seatName",sname)
                                .add("id",ids)
                                .add("idType",idType)
                                .build();
                        Request request = new Request.Builder().url(Constant.Host +"/otn/Order").post(formBody).addHeader("cookie",JSESSIONID).build();
                        Log.i(TAG, "run: tn:"+tn+" startTrainDate:"+startTrainDate+"  seatName:"+seatName+"  id:"+ids+"  idType:"+idType);
                        Call call = okHttpClient.newCall(request);
                        try {
                            Response response = call.execute();
                            String string = response.body().string();

                            // 获取订单数据后，解析为Oreder对象，传入到下一个页面中
                            Order order = new Gson().fromJson(string, Order.class);
                            Intent intent1 = new Intent(chepiaoyuding3Activity.this,chepiaoyuding4Activity.class);
                            intent1.putExtra("order",order);
                            intent1.putExtra("paArray",paArray);
                            startActivity(intent1);

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

            }
        });

        // 显示ActiongBar上的返回按钮
        ActionBar supportActionBar = getSupportActionBar();
        supportActionBar.setDisplayHomeAsUpEnabled(true);
    }

    // 返回按钮中当前页面结束的监听事件
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch ( item.getItemId() ){
            case android.R.id.home:
                chepiaoyuding3Activity.this.finish();
                break;
        }
        return true;
    }


    // 从服务器上获取乘车人数据的方法
    public void queryFromServer(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient okHttpClient = new OkHttpClient();
                SharedPreferences sharedPreferences = getSharedPreferences("userinfo",MODE_PRIVATE);
                String JSESSIONID = sharedPreferences.getString("cookie", "");
                Request request = new Request.Builder().url(Constant.Host +"/otn/TicketPassengerList").addHeader("cookie",JSESSIONID).build();
                Call call = okHttpClient.newCall(request);
                try {
                    Response res = call.execute();
                    String json = res.body().string();
                    listPassenger = new Gson().fromJson(json,new TypeToken<List<Passengers>>() {}.getType());

                    //  从服务器获取乘车人数据后 ， 弹出AlertDialog对话框，将乘车人数据加载到ListView进行展示。

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            LayoutInflater layoutInflater = LayoutInflater.from(chepiaoyuding3Activity.this);
                            View item = layoutInflater.inflate(R.layout.item_alert, null, false);
                            ListView lv = item.findViewById(R.id.lv);
                            final ArrayList<HashMap<String,String>> dataArray = new ArrayList<>();
                            for (int i = 0; i < listPassenger.size(); i++) {
                                Passengers passengers = listPassenger.get(i);
                                HashMap<String,String> hashMap = new HashMap<>();
                                hashMap.put("txtName",passengers.getName());
                                hashMap.put("txtId",passengers.getId());
                                hashMap.put("txtPhone",passengers.getTel());
                                dataArray.add(hashMap);
                            }
                            // 获取到 乘车人数据源dataArray后，将数据放入适配器让Listview展示数据
                            MyAdapter3 myAdapter3 = new MyAdapter3(chepiaoyuding3Activity.this,dataArray);
                            lv.setAdapter(myAdapter3);
                            AlertDialog.Builder alert = new AlertDialog.Builder(chepiaoyuding3Activity.this);
                            alert.setIcon(null)
                                    .setTitle("选择联系人")
                                    .setView(item)
                                    .setPositiveButton("确定",null)
                                    .create()
                                    .show();

                            // 对话框里ListView的点击事件，子项被点击，就将该乘车人的数据加载到Activity当中
                            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    HashMap<String, String> hashMap = dataArray.get(position);
                                    sdataArray.add(hashMap);
                                    paArray.add(hashMap.get("txtName"));
                                    ids += "id="+hashMap.get("txtId");
                                    idType += "idType=身份证";
                                    smyAdapter3.notifyDataSetChanged();
                                    String substring = price.substring(2);
                                    allPrice.setText("订单总额：¥"+(sdataArray.size()*Integer.parseInt(substring)));

                                }
                            });
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    public void confData(){
//        dataArray.clear();
//        for (int i = 0; i < listPassenger.size(); i++) {
//            Passengers passengers = listPassenger.get(i);
//            HashMap<String,String> hashMap = new HashMap<>();
//            hashMap.put("txtName",passengers.getName());
//            hashMap.put("txtId",passengers.getId());
//            hashMap.put("txtPhone",passengers.getTel());
//            dataArray.add(hashMap);
//        }
//        myAdapter3.notifyDataSetChanged();
    }

    private static final String TAG = "chepiaoyuding3Activity";


}